<template>
  <div>
    <nav-bar/>
    <div class="order-main">
      <div class="order-nav w">
        <h4>选择完善您的个人信息:</h4>
      </div>
    </div>
    <div class="order w">
      <el-card class="order-card">
        <h3>{{this.roomType.roomType}}</h3>
        <div class="card-image">
          <el-image fit="fill" :src="getRoomImage[0]" :preview-src-list="getRoomImage"
                    style="width: 200px;height: 100px"></el-image>
        </div>
        <div class="card-text">
          <div>{{new Date()}}</div>
          <div>床型：{{this.roomType.roomBed}}</div>
          <div>房间大小：{{this.roomType.roomSize}}平方米</div>
          <div>房间楼层：{{this.roomType.roomFloor}}楼（如有特殊楼层要求请备注）</div>
          <div>剩余数量：{{this.roomType.roomRemain}}间</div>
        </div>
      </el-card>
      <el-divider></el-divider>
      <el-form :model="orderForm" :rules="orderFormRules" ref="orderFrom" label-position="top"
               label-width="100px" class="order-form">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="orderForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="orderForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input v-model="orderForm.email"></el-input>
        </el-form-item>
        <el-form-item label="订单备注" prop="remark">
          <el-input v-model="orderForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <el-card class="pay-card">
        <div slot="header" class="clearfix">
          <h3>收费标准</h3>
        </div>
        <div class="pay-detail">
          <span class="pay-title">客房费用：</span>
          <span class="pay-text">{{roomType.roomPrice}}元</span>
        </div>
        <div class="pay-detail">
          <span class="pay-title">服务费：</span>
          <span class="pay-text">0元</span>
        </div>
        <el-divider></el-divider>
        <div class="pay-total">
          <span>总费用：</span>
          <span>{{roomType.roomPrice}}元</span>
        </div>
        <el-button type="primary" class="pay-button" @click="submitOrder()">提交订单</el-button>
        <p>> 确认订单默认确认本公司的服务条款的限制</p>
        <p>> 我们将为您推送适合您的推荐信息</p>
      </el-card>
    </div>

    <el-dialog
        title="支付宝扫码支付" :visible="showPayCard" width="240px"
        :close-on-press-escape="false" :close-on-click-modal="false"
        :before-close="payCancel">
      <vueQr :text="qr" :size="200" :margin="10" :correctLevel="0" :whiteMargin="false" ></vueQr>
      <div style="margin: 0 auto;display: inline-block">{{message?message:''}}</div>
    </el-dialog>
  </div>
</template>
<script>
import NavBar from "@/components/common/navbar/NavBar";
import Footer from "@/components/common/footer/Footer";
import {getRoomTypeByIdAndTypeNo} from "@/network/room";
import {doOrder, cancelOrder} from "@/network/pay";
import vueQr from 'vue-qr'
import {baseWsIP} from "@/network/request";
export default {
  name: "Order",
  components: {Footer, NavBar, vueQr},
  data(){
    return{
      roomType:{},
      orderForm:{
        name:'',
        phone:'',
        email:'',
        remark:'',
      },
      orderInfo:{},
      orderFormRules:{
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入正确的电话', trigger: 'blur' },
          { min: 7, max: 11, message: '长度在 7 到 11 个字符', trigger: 'blur' }
        ],
      },
      webSocket:'',
      showPayCard:false,
      qr:'',
      message:'',
    }
  },
  methods:{
    submitOrder(){
      this.$refs.orderFrom.validate( (valid)=>{
        if (valid){
          if (this.webSocket && this.webSocket.readyState === 1) { // 如果连接正常
            //订单数据整理
            let createOrder = {
              aliPayRequest:{
                total_amount:this.roomType.roomPrice,
                subject:this.roomType.roomType,
                body:this.roomType.roomDesc,
              },
              name:this.orderForm.name,
              phone:this.orderForm.phone,
              email:this.orderForm.email,
              remark:this.orderForm.remark,
              roomTypeId:this.$route.query.id,
            }
            doOrder(createOrder).then(res=>{
              this.qr = res.data.data
              this.showPayCard = true
            })
          } else { // 否则重连
            this.initWebSocket()
          }
        }else {
          console.log('表单验证失败')
        }
      })
    },
    payCancel(){
      this.$confirm('订单还未付款，是否取消付款?', '提示', {
        confirmButtonText: '继续付款',
        cancelButtonText: '取消付款',
        type: 'warning'
      }).then(() => {

      }).catch(() => {
        cancelOrder()
        this.$message.info('付款已取消')
        this.closeWebSocket()
        //取消订单
        this.showPayCard = false
      });
    },
    // 初始化webSocket
    initWebSocket() {
      if (!this.webSocket || this.webSocket.readyState !== 1){
        this.webSocket = new WebSocket(baseWsIP('pay',this.$store.getters.getUserInfo.id));
        this.webSocket.onmessage = this.webSocketMsg;
        this.webSocket.onerror = this.webSocketError;
        this.webSocket.onclose = this.closeWebSocket;
      }
    },
    webSocketError() {
      //连接建立失败重连
      this.initWebSocket();
    },
    webSocketMsg(e) {
      this.message = e.data
      if (e.data==='支付成功'){
        setTimeout(()=>{
          this.showPayCard = false
          this.$router.push('/user/order')
        },1000)
      }
    },
    sendWebSocket(data) {
      //数据发送
      this.webSocket.send(JSON.stringify(data));
    },
    closeWebSocket() {
      //关闭
      this.webSocket.close();
    }
  },
  computed:{
    getRoomImage(){
      return this.roomType.roomImages ? this.roomType.roomImages.split('|'):[]
    },
    getUserInfo(){
      return this.$store.getters.getUserInfo
    }
  },
  mounted() {
    getRoomTypeByIdAndTypeNo(this.$route.query).then(res=>{
      this.roomType = res.data.data
    })
    let s = this.$store.getters.getUserInfo
    this.orderForm.name = s.name
    this.orderForm.phone = s.phone
    this.orderForm.email = s.email
    // 连接websocket
    this.initWebSocket();
  },destroyed() {
    this.closeWebSocket()
  },deactivated() {
    this.closeWebSocket()
  },activated() {
    this.initWebSocket();
  }
}
</script>

<style scoped>
  .w {
    width: 1200px;
    margin: 0 auto;
  }
  h3 {
    margin: 0 0 10px 0;
  }
  p {
    margin: 0;
    padding: 0;
  }
  .order {
    /*height: 700px;*/
  }
  .order-main {
    width: 100%;
    box-shadow: 0 5px 5px 0 skyblue;
  }
  .order-nav {
    height: 30px;
  }
  .order-nav h4 {
    line-height: 30px;
    padding: 0;
    margin: 10px 0;
  }
  .order-card {
    margin-top: 10px;
    background-color: #fdf7f7;
  }
  .card-image {
    float: left;
    height: 120px;
  }
  .card-text {
    float: left;
    margin-left: 10px;
  }
  .order-form {
    float: left;
    width: 700px;
  }
  .pay-card {
    float: right;
    margin-top: 20px;
    width: 400px;
  }
  .pay-card h3 {
    height: 50px;
    line-height: 50px;
    font-size: 18px;
    text-align: center;
    margin: 0;
    color: #333;
    background-color: #f4f5f6;
  }
  .pay-detail {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    line-height: 20px;
    color: #333;
    font-weight: 500;
  }
  .pay-title {
  }
  .pay-text {
    font-size: 14px;
    line-height: 16px;
  }
  .pay-total {
    display: flex;
    justify-content: space-between;
  }
  .pay-total span {
    font-size: 16px;
    line-height: 24px;
    font-weight: 700;
  }
  .pay-button {
    width: 100%;
    margin: 30px auto;
  }
</style>